package com.aaa.dao;

import com.aaa.ann.ColumnAnn;
import com.aaa.ann.EntityAnn;
import com.aaa.ann.SetIdAnn;
import com.aaa.entity.Dept;
import com.aaa.util.DbUtil;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：zhouhangyong
 * @date ：Created in 2022/6/15 15:07
 * @description：daoc层实现类
 * @modified By：
 * @version:
 */
public class MyDaoImpl<T> implements MyDao<T> {
    DbUtil dbUtil = new DbUtil();

    /**
     * @return
     * @Author zhouhangyong
     * @Description 创建一个添加数据的数据库链接//TODO
     * @Date 15:10 2022/6/15
     * @Param obj输入一个实体对象
     **/
    @Override
    public void saveEntity(T obj) throws IllegalAccessException, SQLException {
        //得到输入对象的类
        Class<?> objClass = obj.getClass();
        //获得实体的注解值
        EntityAnn entityAnn = objClass.getAnnotation(EntityAnn.class);
        //获取表名
        String tableName = entityAnn.tableName();
        //获取列名
        Field[] fields = objClass.getDeclaredFields();
        //coumnNames封装了所有的键名
        StringBuffer coumnNames = new StringBuffer();
        //coumnValues封装所有的列值
        List<Object> coumnValues = new ArrayList<>();

        for (Field field : fields) {

            //开启访问权限
            field.setAccessible(true);
            ColumnAnn columnAnn = field.getAnnotation(ColumnAnn.class);
            if (columnAnn != null) {
                //获取列名
                String columnName = columnAnn.columnName();
                coumnNames.append(columnName).append(",");
                //获取列值
                Object colunbValue = field.get(obj);
                coumnValues.add("'" + colunbValue + "'");
            }

        }
        coumnNames.deleteCharAt(coumnNames.length() - 1);
        String replaceValue = coumnValues.toString().replace("[", "").replace("]", "");
        StringBuffer sql = new StringBuffer("insert into ");
        //拼接sql语句
        sql.append(tableName).append("(").append(coumnNames).append(")").append("values(").append(replaceValue).append(")");

        Connection dbUtilConn = dbUtil.getConn();
        PreparedStatement preparedStatement = dbUtilConn.prepareStatement(sql.toString());
        int executeUpdate = preparedStatement.executeUpdate();
        preparedStatement.close();
        dbUtilConn.close();
        System.out.println(executeUpdate);
    }

    @Override
    public void deleteEntity(T obj) throws IllegalAccessException, SQLException {
        Class<?> objClass = obj.getClass();
        EntityAnn entityAnn = objClass.getAnnotation(EntityAnn.class);
        String tableName = entityAnn.tableName();
        Field[] fields = objClass.getDeclaredFields();
        StringBuffer stringBuffer = new StringBuffer("delete from ").append(tableName).append(" where ");
        String columnNmae = null;
        Object columnValue = null;
        for (Field field : fields) {
            SetIdAnn setIdAnn = field.getAnnotation(SetIdAnn.class);
            field.setAccessible(true);
            if (setIdAnn != null) {
                columnNmae = setIdAnn.columnName();
                columnValue = field.get(obj);
            }
        }
        stringBuffer.append(columnNmae).append(" in("+columnValue+")");
        System.out.println(stringBuffer);
        Connection deleteConn = dbUtil.getConn();
        PreparedStatement preparedStatement = deleteConn.prepareStatement(stringBuffer.toString());
        int executeUpdate = preparedStatement.executeUpdate();
        System.out.println(executeUpdate);
        preparedStatement.close();
        deleteConn.close();

    }


    @Override
    public void updateEntity(T obj) throws IllegalAccessException, SQLException {
        Class<?> objClass = obj.getClass();
        EntityAnn entityAnn = objClass.getAnnotation(EntityAnn.class);
        String tableName = entityAnn.tableName();
        Field[] fields = objClass.getDeclaredFields();
        List<Object> objectList = new ArrayList<>();
        StringBuffer stringBuffer = new StringBuffer(" update " + tableName + " set ");
        String columnNmae = "";
        Object columnValue = null;
        for (Field field : fields) {
            //开启访问权限

            ColumnAnn columnAnn = field.getAnnotation(ColumnAnn.class);
            if (columnAnn != null) {

                field.setAccessible(true);
                //获取列名
                String columnName = columnAnn.columnName();
                System.out.println(columnName);
                stringBuffer.append(columnName + "=?,");
                //获取键值
                Object columnValues = field.get(obj);
                objectList.add(columnValues);
            } else {
                field.setAccessible(true);
                SetIdAnn setIdAnn = field.getAnnotation(SetIdAnn.class);
                columnNmae = setIdAnn.columnName();
                columnValue = field.get(obj);
                System.out.println(columnValue);
            }
        }
        objectList.add(columnValue);
        StringBuffer newbuffer = stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        newbuffer.append(" where 1=1 and ").append(columnNmae).append("=?");
        Connection updateConn = dbUtil.getConn();
//        System.out.println(newbuffer);
        PreparedStatement updateStatement = updateConn.prepareStatement(newbuffer.toString());
        for (int i = 0; i < objectList.size(); i++) {
            updateStatement.setObject(i + 1, objectList.get(i));
        }
        int executeUpdate = updateStatement.executeUpdate();
        updateStatement.close();
        updateConn.close();
        System.out.println(executeUpdate);
    }

    @Override
    public List<Map> selectEntity(String name) throws SQLException {
        StringBuffer stringBuffer = new StringBuffer("select * from " + name);
        Connection selectConn = dbUtil.getConn();
        PreparedStatement statement = selectConn.prepareStatement(stringBuffer.toString());
        ResultSet resultSet = statement.executeQuery();
        ResultSetMetaData resultSetMetaData = statement.getMetaData();
        List<Map> list = new ArrayList<>();
        while (resultSet.next()) {
            Map<Object, Object> map = new HashMap<>();
            for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
                map.put(resultSetMetaData.getColumnName(i).toLowerCase(), resultSet.getObject(i));
            }
            list.add(map);
        }


        return list;
    }


}

class Text {
    public static void main(String[] args) throws IllegalAccessException, SQLException {
        MyDao myDao = new MyDaoImpl();
//        myDao.saveEntity(new Dept(60,"qy159","郑州"));
//        myDao.updateEntity(new Dept(120052, "qy190", "郑州"));
//        List<Map> selectEntity = myDao.selectEntity("dept");
//        for (Map map : selectEntity){
//            System.out.println(map);
//        }
        Dept dept = new Dept();
        dept.setDeptid(120052);
        myDao.deleteEntity(dept);

    }
}
